# Create your views here.
from django.template.loader import get_template
from django.template import Context,RequestContext

from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.conf import settings

import traceback,sys

#Ajax new implementation
from django.utils import simplejson
import MySQLdb


def get_status_aib(template_name='menu_dir_temp_green.html'):
    try:

        
        db = MySQLdb.connect(user = settings.STOCKS_DB_USER, 
                            db = settings.STOCKS_DB_NAME, 
                            passwd = settings.STOCKS_DB_PASS, 
                            host = settings.STOCKS_DB_HOST, 
                            port = settings.STOCKS_DB_PORT)
               
        #PROD
        #'''
        query_select_start = """
                        SELECT `id_trade`, `ativo_cod`, `lot_size`, `valor_compra`, `data_compra`, `valor_venda`, `data_venda`, `aberto`, `comissao_compra`, `comissao_venda`, `data_real_compra`, `data_real_venda` 
                        FROM `stocks_db`.`open_trades` 
                        ORDER BY `data_compra` ASC 
                        LIMIT 1;
                        """
        query_select_ultima = """
                        SELECT `id_trade`, `ativo_cod`, `lot_size`, `valor_compra`, `data_compra`, `valor_venda`, `data_venda`, `aberto`, `comissao_compra`, `comissao_venda`, `data_real_compra`, `data_real_venda` 
                        FROM `stocks_db`.`open_trades` 
                        ORDER BY `data_compra` DESC 
                        LIMIT 1;
                        """  
        query_select_open = """
                        SELECT `id_trade`, `ativo_cod`, `lot_size`, `valor_compra`, `data_compra`, `valor_venda`, `data_venda`, `aberto`, `comissao_compra`, `comissao_venda`, `data_real_compra`, `data_real_venda` 
                        FROM `stocks_db`.`open_trades` 
                        WHERE data_venda is NULL
                        ORDER BY `data_compra` ASC 
                        LIMIT 1;
                        """                                                  
        #'''
        #print "query_select: %s" % (query_select)
        response_dict = {}
        cursor = db.cursor()
        cursor.execute(query_select_start)
        response_dict['response_status_aib_start'] = cursor.fetchall()
        #cursor = db.cursor()
        cursor.execute(query_select_ultima)
        response_dict['response_status_aib_ultima'] = cursor.fetchall()
        #cursor = db.cursor()
        cursor.execute(query_select_open)
        response_dict['response_status_aib_open'] = cursor.fetchall()
        
        if len(response_dict['response_status_aib_open'])>0:
            response_dict['response_status_aib_open'] = "Nenhuma"
            
        response_dict['fields_status_aib'] = cursor.description
        response_dict['template_name'] = template_name
        db.close()
        
        return response_dict
    except:
        exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
        traceback.print_exception(exceptionType, exceptionValue, exceptionTraceback,
                          limit=2, file=sys.stdout) 

def get_status_aib_ajax_html(request):
    try:
        response_dict=get_status_aib()
        if response_dict:
            t = get_template(response_dict['template_name'])
            c = RequestContext(request,response_dict)
            html = t.render(c)
            return HttpResponse(html, mimetype='text/html; charset=UTF-8')
        else:
            return HttpResponse(simplejson.dumps('UN'), mimetype='application/json; charset=UTF-8')
    except:
        exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
        traceback.print_exception(exceptionType, exceptionValue, exceptionTraceback,
                          limit=2, file=sys.stdout) 

def get_status_aib_ajax_json(request):
    try:
        #print "ultimo_time:%s" % (ultimo_time)        
        response_dict=get_status_aib()
        if response_dict:
            return HttpResponse(simplejson.dumps(response_dict['response_status_aib_ultima']), mimetype='application/json; charset=UTF-8')
        else:
            return HttpResponse(simplejson.dumps('UN'), mimetype='application/json; charset=UTF-8')
    except:
        exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
        traceback.print_exception(exceptionType, exceptionValue, exceptionTraceback,
                          limit=2, file=sys.stdout) 